package cn.edu.zjgsu.ito.controller;

import cn.edu.zjgsu.ito.interceptor.AdminControllerInterceptor;
import cn.edu.zjgsu.ito.service.AdminExportScoreService;
import cn.edu.zjgsu.ito.service.ServiceFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;

@Before(AdminControllerInterceptor.class)
public class AdminExportScoreController extends Controller {
		/*
		 * 张虎涛
		 * 2016/06/01
		 */
		private AdminExportScoreService adminExportScoreService =ServiceFactory.createAdminExportScoreService();
		private int uuid;
		private List<Record> records;
		private Record record;
		public static final DateFormat formatter=new SimpleDateFormat("yyyy-MM-dd-HH：mm");
		
		/**
		  *  导出Excel
		 * @throws FileNotFoundException 
		  * 
		  */
	 	public void exportExcel() throws FileNotFoundException
	 	{

	 		String uuid=getPara("uuid");
	 		Date d=new java.util.Date();
	 		

	 		String filedir=PathKit.getWebRootPath();
	 		filedir=filedir+"\\WEB-INF\\download\\";
	 		
	        deleteFile(new File(filedir));//清空缓存区
	         
	 		String courseName;
	 		
	 		
	 		records=adminExportScoreService.CourseGrade(uuid);
	 		record=adminExportScoreService.TTT(uuid);
	 		courseName=records.get(0).get("courseName");
	 		courseName=courseName.replace(" ", "-");
	 		courseName=courseName+"成绩汇总表("+formatter.format(d)+").xls";
	 		
	 		OutputStream out = new FileOutputStream(filedir+courseName);	 		
	 		System.out.println(filedir+courseName);
	 		adminExportScoreService.exportExcel(records, out,record);
	 		String outpath=filedir+courseName;
	 		
	 		renderFile(new File(outpath));
	 	}
	 	
	 	 public void deleteFile(File oldPath) {
	          if (oldPath.isDirectory()) {
	           File[] files = oldPath.listFiles();
	           for (File file : files) {
	             deleteFile(file);
	           }
	          }else{
	            oldPath.delete();
	          }
	        }

}
